<template>
  <div>
    <van-cell-group border>
      <van-field
        v-model="yzm"
        label="短信验证码"
        placeholder="请输入验证码"
        autofocus
      >
        <template #button>
          <van-button size="small" @click="sendmsg" :disabled="buttonFlag" type="primary">{{txt}}</van-button>
        </template>
      </van-field>
    </van-cell-group>
    <div class="nextbtn">
      <van-button
        type="danger"
        round
        block
        :disabled="flag"
        @click="next"
        >下一步</van-button
      >
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import { Toast } from 'vant';

Vue.use(Toast);
import {dosendmsgcode,docheckcode} from "../../api/user"
export default {
  data() {
    return {
      yzm: "",
      txt:"发送验证码",
      time:60,
      buttonFlag:false,
    };
  },
  methods: {
    sendmsg(){
      //效果上是倒计时
      const timer = setInterval(()=>{
        this.time--
        if (this.time==0) {
          clearInterval(timer)
          this.buttonFlag = false
          this.txt = "发送验证码"
          this.time=60;
        } else {
          this.txt = this.time+"s后可以重新发送"
          this.buttonFlag = true;
        }
      },1000)
      //实际上真实也需要发请求
      setTimeout(()=>{
        dosendmsgcode({tel:localStorage.getItem("tel")}).then((res)=>{
          console.log(res.data.data);
          this.yzm = res.data.data
        })
      },1000)
    },
    next(){
      docheckcode({tel:localStorage.getItem("tel"),telcode:this.yzm}).then(res=>{
        console.log(res);
        switch (res.data.code) {
          case '10007':
            Toast('验证码错误');
            break;
          case '200':
            this.$router.push("/register/three")
            break;
          default:
            break;
        }
      })
    }
  },
  computed: {
    flag(){
      if (/^\d{5}$/.test(this.yzm)) {
        return false;//红色
      }else{
        return true;//灰色禁用
      }
    }
  }
};
</script>

<style scoped>
.nextbtn {
  width: 80%;
  margin: 0.1rem auto;
}
</style>